package com.rc.saas.mini.minip.init;

import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.tenant.TenantExample;
import com.rc.saas.mini.service.tenant.TenantService;
import com.rc.saas.mini.weixin.RedisWxConfiguration;
import com.rc.saas.mini.weixin.RedisWxConfigurationLoader;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 小程序初始化启动器，启动时就要开始加载所有配置信息
 * 启动完成的时候初始化所有运营商的配置信息并保存到Redis中
 * @author wangzhengwei
 * @create 2021/5/6
 */
@Component
public class MiniApplicationRunner implements ApplicationRunner {
    private static Logger logger = LogManager.getLogger(MiniApplicationRunner.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private RedisWxConfigurationLoader redisWxConfigurationLoader;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<Tenant> list = tenantService.selectByExample(new TenantExample());
        for (Tenant tenant:list){
            if (StringUtils.isNotBlank(tenant.getMinipOriginalid())){
                //初始化配置类
                RedisWxConfiguration redisWxConfiguration = new RedisWxConfiguration(tenant.getMinipOriginalid(),
                        tenant.getMinipAppid(), tenant.getMinipSecret(), tenant.getMinipToken(),
                        tenant.getWechatPayMchid(), tenant.getWechatPaySecret(),
                        tenant.getTenantCode(), tenant.getTenantPrefix(), tenant.getTenantLogoImg());

                //将配置类保存到Redis缓存中,有效期365天
                if (StringUtils.isNotBlank(redisWxConfiguration.getOriginalid())) {
                    redisWxConfigurationLoader.set(redisWxConfiguration);
                    logger.info("加载微信小程序配置信息保存到Redis缓存中:{}", redisWxConfiguration);
                }
            }
        }
    }
}
